package org.gpslw.util;

import lombok.extern.slf4j.Slf4j;
import org.geotools.api.data.DataStore;
import org.geotools.api.data.FeatureSource;
import org.geotools.api.feature.simple.SimpleFeature;
import org.geotools.api.feature.simple.SimpleFeatureType;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.geopkg.GeoPkgDataStoreFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class GpkgReader {

    /**
     * 读取GeoPackage文件(对应多个图层)
     * @param gpkgPath
     * @return
     * @throws IOException
     */
    public static Map<String, List<SimpleFeature>> readGpkgFile(String gpkgPath) throws IOException {
        //key: typeName, value: features
        Map<String, List<SimpleFeature>> result = new HashMap<>();
        // 创建 GeoPackage 数据源工厂
        GeoPkgDataStoreFactory factory = new GeoPkgDataStoreFactory();
        // 设置参数
        Map<String, Object> params = new HashMap<>();
        params.put(GeoPkgDataStoreFactory.DATABASE.key, new File(gpkgPath)); // 指定 .gpkg 文件路径
        params.put(GeoPkgDataStoreFactory.EXPOSE_PK.key, true); // 是否启用 loose bbox 模式（可选）
        // 创建 DataStore
        DataStore dataStore = factory.createDataStore(params);
        // 获取所有图层名称
        String[] typeNames = dataStore.getTypeNames();
        log.info("Available layers in GeoPackage:");
        for (String typeName : typeNames) {
            List<SimpleFeature> featureList = new ArrayList<>();
            // 获取 FeatureSource
            FeatureSource<SimpleFeatureType, SimpleFeature> source = dataStore.getFeatureSource(typeName);
            // 获取图层的范围
            ReferencedEnvelope bounds = source.getBounds();
            log.info("Bounds: " + bounds);
            // 读取所有要素
            FeatureCollection<SimpleFeatureType, SimpleFeature> features = source.getFeatures();
            FeatureIterator<SimpleFeature> iter = features.features();
            while (iter.hasNext()) {
                SimpleFeature feature = iter.next();
                featureList.add(feature);
            }
            result.put(typeName, featureList);
        }
        // 关闭数据源
        dataStore.dispose();
        return result;
    }
}

